<script setup>
import { InfoFilled,Plus } from '@element-plus/icons-vue'
import { useUserStore  } from '../stores/user'
import getUser  from "../api/getuser.js"
import AllUser from '../api/getAllUser.js';
import getUserById from '../api/getUserById.js';
import getUserEntity from "../api/getUserEntity";
import imageShow from './imageShow.vue';
import { useRouter } from 'vue-router';
import isAdmin  from '../api/isAdmin';
import sender from '../api/sendConfirmCode.js'
import getImage from '../api/getImage';
import {ref ,onBeforeMount,computed, reactive} from "vue"
import getArticleList from "../api/getArticleList.js"
import updateUserInform from '../api/updateUserInform.js'
import display from "../api/getArticleNeedConfrim.js"
import updateArticleAdmin from '../api/updateArticleAdmin'
import getEmail from '../api/getEmail.js'
import change from "../api/changePassword.js"
import { ElMessage } from 'element-plus';
import getCarousel from '../api/getCarousel.js'
import uploadCarousel from '../api/uploadCarousel.js'
import delCarousel from '../api/delCarousel.js'
import updateCarousel from '../api/changeCarousel.js'
import isSuperAdmin from '../api/isSuperAdmin.js'
import adminChangeRole from '../api/adminChangeRole.js'
import superAdminChangeRole from '../api/superAdminChangeRole.js'
const addCarousel = ref({
    title:"",
    description:"",
    imageUrl:"",
    imageId:"",
    link:""
})
const AdminSetVisible = ref(false)
const activeName = ref('1')
const timeOut = ref(0)
const userId = ref(localStorage.getItem("userId"))
const userInform = useUserStore()
const imageValue = ref("")
const user = ref({})
const userInforms= ref({})
const use = useRouter()
const confirm_code = ref("")
const imageUrl = ref("")
const image_id = ref("")
const articles = ref([])
const flag = ref(false)
const an_state = ref(false)
const centerDialogVisible = ref(false)
const email = ref("")
const confirm_Box = ref(false)
const super_admin_state = ref(false)
const patrn=/^([\w-.])$/
const changePassword = reactive([{
    oldPassword :"" ,
    newPassword :"" ,
    confirmPassword :"" 
}])
const visible_update = ref(false)
const visible = ref(false)
const carousel_list = ref([])
const CarouselSetVisible = ref(false)
const size = 10
const page = ref(0)
const userList = ref([])
const carousel_item = ref({})
const url = "http://localhost:5173/api/image/upload?token=Bearer " + localStorage.getItem("jwttoken")
try{
        if(userInform.userId === ""){
        getUser({
        }).then(function (response) {
        if(response.status == 200 && response.data.userId!=undefined)
        {
            userInform.userId = response.data.userId ;
            userInform.username = response.data.userName ;
            userInform.image = response.data.imageId;
            userInform.article =  response.data.articleId ;
        }
        else {
            localStorage.removeItem("jwttoken");
            localStorage.removeItem("userId");
        }
        })
        }
    }
    catch(error)
    {
        loading.value = false ;
        console.error(error);
    }

onBeforeMount(()=>{
    isAdmin().then((res)=>{
        if(res.status = 200)
        an_state.value= true
    })

    getUserById(localStorage.getItem("userId")).then((res)=>{
        if(res.status == 200)
        {
            userInforms.value = res.data
            getImage(userInforms.value.imageId).then((res)=>
            {
                if(res.status == 200)
                imageValue.value = res.data 
            })
            console.log(res.data)
        }
    })

    isSuperAdmin().then((res)=>{
        if(res.status == 200)
        super_admin_state.value = true
    })
    
})

function delCarouselFunc(id){
    delCarousel(id).then((res)=>{
        if(res.status == 200)
        {
            ElMessage.success("删除成功")
            openCarouselSet()
        }

    })
}

function AdminChangeState(data)
{
    updateArticleAdmin({
            id:data.id,
            state:true,
        }).then((res)=>{
            if(res.status == 200)
            {
                articles.value=articles.value.filter((e)=>{
                    return e.id != data.id
                })
                ElMessage.success("修改成功")
            }
    })
}

function openThePanel()
{
    centerDialogVisible.value = true
    display().then((res)=>{
        if(res.status == 200)
        articles.value = res.data
    console.log(res.data)
    })
}

function timerHandler () {
    setInterval(()=>{timeOut.value--},1000)
}

function submitUser()
{
    updateUserInform(
        userInforms.value.userName ,
        userInforms.value.imageId
        ).then((res)=>{
            if(res.status == 200)
            ElMessage.success("修改成功");
        })
}

function confirmPassword ()
{

    if( changePassword.newPassword == changePassword.oldPassword)
    ElNotification({
    title: '验证失败',
    message: '新密码不能和旧密码相同',
    type: 'error',
    })
    else {
    if(patrn.exec(changePassword.newPassword) && changePassword.newPassword!="" && changePassword.newPassword.length()>8 && changePassword.newPassword.length()<20  )
    {
        if(changePassword.newPassword == changePassword.confirmPassword)
        {
            getEmail().then((res)=>{
            if(res.status == 200)
            {email.value = res.data
            confirm_Box.value = true
            sendConfirmCode();}
            else{
                ElNotification({
                title: '发送失败',
                message: '未获取到邮箱',
                type: 'error',
                })
            }
            })

        }
        else{
            ElNotification({
                title: '验证失败',
                message: '两次密码不相同',
                type: 'error', 
            })}
    }
    else {
    ElNotification({
    title: '验证失败',
    message: '密码的长度要大于8位且小于20位并确保由字母、数字、特殊字符组成',
    type: 'error',
    })
    }
}
}

function changePasswordFunc(){
        change({
            newPassword: changePassword.newPassword,
            oldPassword: changePassword.oldPassword
        },confirm_code.value).then((res) => {
            if (res.status == 200)
            {
                ElMessage.success("修改成功")
                confirm_Box.value= false
            }
        })
    }

function sendConfirmCode(){
        if(email.value.trim === "" || email.value == undefined || email.value === "")
        {
            ElMessage({message:'请输入邮箱',
            type:"error"})
            return null
        }
            timeOut.value = 180
            timerHandler()
            sender(email.value).then(
            (res)=>{
            if( res.status == "200" ){
            }
            }
            )
        }
    function successHandler_2(res,file)
    {
        addCarousel.value.imageId =res
        imageUrl.value = URL.createObjectURL(file.raw);
    }

    function successHandler (res,file){ 
        image_id.value =res
        imageUrl.value = URL.createObjectURL(file.raw);
        userInforms.value.imageId = image_id.value
    }
    function beforeAvatarUpload(file) {
        const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
            ElMessage.error('上传图片只能是 JPG / PNG 格式!');
        }
        if (!isLt2M) {
            ElMessage.error('上传图片大小不能超过 2MB!');
        }


        return isJPG && isLt2M;
    }

    function openCarouselSet(){
        CarouselSetVisible.value =true
        getCarousel().then((res)=>{
            if (res.status == 200){
                carousel_list.value = res.data
            }
        })
    }

    function addCarouselFunc(){
        console.log(addCarousel.value)
        if(addCarousel.value.link!="" && addCarousel.value.title != "" && (addCarousel.value.imageUrl != "" || addCarousel.value.imageId!="") )
        uploadCarousel(addCarousel.value).then((res)=>{
            if(res.status == 200)
            {
                ElMessage.success("添加成功")
                openCarouselSet()
                visible.value = false
            }
            visible.value = false
        })
    }

    function updateCarouselFunc(item){
        updateCarousel(item).then((res)=>{
            if (res.status == 200){
                ElMessage.success("修改成功")
            }
        })
    }
    function updateCarouselBtn(item){
        visible_update.value = true ;
        carousel_item.value = item
    }

    function adminSet(){
        AdminSetVisible.value = true ;
        getAllUser()
    }

    function adminSet_Btn_add(){
        page.value = (Number)(page.value) + 1
        getAllUser()
    }

    function adminSet_Btn_remove(){
        page.value = (Number)(page.value) - 1
        getAllUser()
    }

    function adminSet_Btn(){
        if((Number)(page.value)<=0)
        page.value = 0
        getAllUser()
    }

    function adminSet_Btn_Set_1(id,role){
        superAdminChangeRole(id,role).then((res)=>{
            if(res.status == 200 )
            {
                ElMessage.success("修改成功")
                adminSet_Btn()
            }
        })
    }

    function adminSet_Btn_Set_2(id){
        adminChangeRole(id).then((res)=>{
            if(res.status == 200 )
            {
                ElMessage.success("修改成功")
                adminSet_Btn()
            }
        })
    }
    const nextPage = ref(true)
    function getAllUser(){
        AllUser({
            page:page.value,
            size:size
        }).then((res)=>{
            if(res.status == 200){
                let list = res.data
                console.log(list)
                if(list.length > 0)
                {
                    userList.value=list
                    nextPage.value = true
                }
                if(list.length < 10)
                nextPage.value = false
                if(list.length == 0)
                {
                    nextPage.value = false
                    page.value = (Number)(page.value) - 1
                    getAllUser()
                }
            }
        })
    
    }

</script>

<template>
    <el-container>
    <el-header style="width: 100%;">
        <Header></Header>
    </el-header>
    <el-main>
    <div style="height: 80vh;width: 80%; position: relative; left: 10%;   top: 12vh  ; margin-bottom: 1rem;">
    
    <div class="demo-collapse">
    <el-collapse v-model="activeName" accordion>
        <el-collapse-item  name="1">
            <template #title>
            可见信息<el-icon class="header-icon">
                <info-filled />
            </el-icon>
            </template>
            <div>
                <el-card>
                    <template #header>
                    <div>
                        <el-avatar class="image-box" shape="square" :size="100" :src="imageValue" />    
                        <div style="float: right; width: 87%;">
                        用户编号：<span>{{ userInforms.userId }}</span>
                        <br> 
                        用户名： <span>{{ userInforms.userName }}</span>
                        <br>
                        收录： <span>{{ userInforms.id }}</span>
                        </div>
                    </div>
                    
                    </template>
                    <div>
                        <el-button @click="use.push('/selfInform?userId='+userInforms.userId)" text>查看详情</el-button> 
                        <el-button @click="flag = true" text>修改</el-button>
                    </div>
                    <template #footer> </template>
                </el-card>
            </div>
            <div>
            注：收录id 编号等 是作为用户唯一标识号无法进行修改的...
            </div>
        </el-collapse-item>
        <el-collapse-item title="修改密码" name="2">
            <div>
                <el-card>
                    <template #header>
                    <div>
                        <el-avatar class="image-box" shape="square" :size="100" :src="imageValue" />    
                        <div style="float: right; width: 87%;">
                        用户编号：<span>{{ userInforms.userId }}</span>
                        <br> 
                        用户名： <span>{{ userInforms.userName }}</span>
                        </div>
                    </div>
                    </template>
                    <div style="margin-left: 10%;"> 
                        <div>
                        <span>旧密码：</span>
                        <input v-model="changePassword.oldPassword" type="password" required/>
                        <span class="bar"></span>
                        </div>
                        <br> 
                        <div>
                        <span>新密码：</span>
                        <input v-model="changePassword.newPassword" type="password" required/>
                        <span class="bar"></span>    
                        </div>
                        <br> 
                        <div>
                        <span>验证密码：</span>
                        <input @blur="confirmPassword" v-model="changePassword.confirmPassword" type="password" required/>
                        <span class="bar"></span>    
                        </div>
                        
                        
                        <br> 
                        <div v-if="confirm_Box">
                            <span> 已为{{ email }}发送了一个验证码： </span> 
                            <div>
                                <input @blur="changePasswordFunc" type="text" v-model="confirm_code" required/> <span v-show="timeOut>0" style="margin-left:4%; color : #999" >有效时间:{{ timeOut }}</span>
                            </div>
                        </div>
                    </div>
                </el-card>
            </div>
        </el-collapse-item>
        <el-collapse-item title="群组" name="3">
            <div>
                <el-button @click="use.push('forum')" text> 进入群组页面 </el-button>
            </div>
        </el-collapse-item>
        <el-collapse-item v-if="an_state" title="其他设置" name="4">
            <div>
                <el-button v-show="an_state" @click="openThePanel" text>审核</el-button>
                <el-button v-show="an_state" @click="openCarouselSet" text>跑马灯设置</el-button>
                <el-button v-show="super_admin_state || an_state" @click="adminSet" text>用户管理</el-button>
            </div>
        </el-collapse-item>
        </el-collapse>
    </div>
    </div>
    </el-main>
    </el-container>
    
    <el-drawer
        v-model="flag"
        :append-to-body="true"
        :before-close="handleClose"
        >
            <div> 用户名： <el-input v-model="userInforms.userName"></el-input> </div>
            <br>
            <div>
                封面：<br>
                <imageShow style="width: 160px; height: 160px;" :value="userInforms.imageId"></imageShow></div>
                <el-upload
                class="avatar-uploader"
                :action="url"
                :show-file-list="true"
                :on-success = "successHandler"
                :before-upload="beforeAvatarUpload">
                
                <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
                <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
                </el-upload>
            <br>
            <div><el-button text @click="submitUser">   提交  </el-button></div>
    </el-drawer>
    <el-dialog v-model="centerDialogVisible" title="审核" width="60%" center>
        <span>
        注：以下的文章是不可见的
        </span>
        <el-table :data="articles" style="width: 100%">
                <el-table-column type="expand">
                <template #default="scope">
                    <div m="4">
                    <p m="t-0 b-2">id: {{ scope.row.id }}</p>
                    <p m="t-0 b-2">作者: {{ scope.row.author }}</p>
                    <p m="t-0 b-2">发布者: <el-link @click="use.push('/selfInform?userId='+scope.row.userId)">{{ scope.row.userId }}</el-link> </p>
                    <p m="t-0 b-2">类型: <el-tag size="small">{{ scope.row.type }}</el-tag> </p>
                    <p m="t-0 b-2">发布时间: {{ scope.row.authorCreatedTime }}</p>
                    <p>封面 <imageShow style="width: 50px; height: 50px;" :value="scope.row.imageId"></imageShow></p>
                    <h3>{{ scope.row.title }}</h3>
                    <div v-html="scope.row.content" :border="childBorder">
                    </div>
                    </div>
                    <el-button @click="AdminChangeState(scope.row)" text>发布</el-button>
                </template>
                </el-table-column>
                <el-table-column prop="id" label="编号" width="240" />
                <el-table-column prop="title" label="标题" width="280" />
                <el-table-column prop="author" label="作者" width="180" />
                <el-table-column prop="authorCreatedTime" label="发布时间" width="180" />
                <el-table-column prop="userId" label="发布id" width="220" />
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="AdminChangeState(scope.row)">发布</el-button>
                    </template>
                </el-table-column>
                
            </el-table>  
    </el-dialog>
    <el-dialog v-model="CarouselSetVisible" title="列表" width="60%" center>
        <span>
        注：以下是会显示在主页的走马灯
        </span>
        <el-table :data="carousel_list" style="width: 100%">
                <el-table-column prop="id" label="编号" width="60" />
                <el-table-column prop="title" label="标题" width="180" />
                <el-table-column prop="description" label="详情" width="180" />
                <el-table-column prop="link" label="链接" width="180" />
                <el-table-column prop="imageId" label="图像id" width="220" />
                <el-table-column prop="imageUrl" label="图像链接" width="240" />
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="delCarouselFunc(scope.row.id)">删除</el-button>
                        <el-button link type="primary" size="small" @click="updateCarouselBtn(scope.row)">更新</el-button>
                    </template>
                </el-table-column>
                
            </el-table>       
        <template #footer>
        <span class="dialog-footer">
            <el-popover :visible="visible" placement="bottom" :width="400">
                <p>添加跑马灯</p>
                <span>标题：</span><el-input v-model="addCarousel.title"/><br>
                <span>链接：</span><el-input v-model="addCarousel.link"/><br>
                <span>详情：</span><el-input v-model="addCarousel.description"/><br>
                <span>图片链接:</span><el-input v-model="addCarousel.imageUrl"/><br>
                <span>上传图片:</span>
                <el-upload
                class="avatar-uploader"
                :action="url"
                :show-file-list="true"
                :on-success = "successHandler_2"
                :before-upload="beforeAvatarUpload">                
                <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
                <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
                </el-upload>
                <span style="font-size: 12px;">如果同时上传图片和图片链接,会默认执行图片链接而非上传后的图片</span>
                <div style="text-align: right; margin: 0">
                <el-button size="small"  @click="visible = false">取消</el-button>
                <el-button size="small" type="primary" @click="addCarouselFunc()">提交</el-button>
                </div>
                <template #reference>
                <el-button @click="visible = true">添加</el-button>
                </template>
            </el-popover>
            
        </span>
        </template>

    </el-dialog>

    <el-drawer v-model="visible_update" title="更新对话框" width="40%" center>
                            <p>添加跑马灯</p>
                            <span>标题：</span><el-input v-model="carousel_item.title"/><br>
                            <span>链接：</span><el-input v-model="carousel_item.link"/><br>
                            <span>详情：</span><el-input v-model="carousel_item.description"/><br>
                            <span>图片链接:</span><el-input v-model="carousel_item.imageUrl"/><br>
                            <span>上传图片:</span>
                            <el-upload
                            class="avatar-uploader"
                            :action="url"
                            :show-file-list="true"
                            :on-success = "successHandler_2"
                            :before-upload="beforeAvatarUpload">                
                            <img v-if="carousel_item.imageUrl != ''" :src="carousel_item.imageUrl" class="avatar">
                            <imageShow v-else-if="carousel_item.imageId !=''" :value="carousel_item.imageId"  class="avatar"></imageShow>
                            <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
                            </el-upload>
                            <span style="font-size: 12px;">如果同时上传图片和图片链接,会默认执行图片链接而非上传后的图片</span>
                            <div style="text-align: right; margin: 0">
                            <el-button size="small"  @click="visible_update = false">取消</el-button>
                            <el-button size="small" type="primary" @click="updateCarouselFunc(carousel_item)">提交</el-button>
                            </div>
    </el-drawer>

    <el-dialog v-model="AdminSetVisible" title="用户管理" width="60%" center>
        <el-table :data="userList" style="width: 100%">
                <el-table-column type="expand">
                <template #default="scope">
                    <div m="4">
                    <p m="t-0 b-2">id: {{ scope.row.id }}</p>
                    <p m="t-0 b-2">账户名: <el-tag size="small">{{ scope.row.username }}</el-tag></p>
                    <p m="t-0 b-2">权限: <el-tag size="small">{{ scope.row.role }}</el-tag> </p>
                    <p m="t-0 b-2">地址: <el-tag size="small">{{ scope.row.address }}</el-tag> </p>
                    <p m="t-0 b-2">邮件: <el-tag size="small">{{ scope.row.email }}</el-tag></p>
                    </div>
                    <el-button v-if="scope.row.role != 'banned' && an_state && !super_admin_state  && (scope.row.role != 'ROLE_ADMIN' && scope.row.role != 'ROLE_SUPERADMIN')" link type="primary" size="small" @click="adminSet_Btn_Set_2(scope.row.id)">封禁</el-button>
                    <el-button v-if="scope.row.role == 'banned' && an_state && !super_admin_state  && (scope.row.role != 'ROLE_ADMIN' && scope.row.role != 'ROLE_SUPERADMIN')" link type="primary" size="small" @click="adminSet_Btn_Set_2(scope.row.id)">设为用户</el-button>
                    <el-button  v-if="scope.row.role != 'banned' && super_admin_state  && scope.row.role != 'ROLE_SUPERADMIN'" @click="adminSet_Btn_Set_1(scope.row.id,'banned')" text>封禁</el-button>
                    <el-button  v-if="scope.row.role == 'ROLE_USER' && super_admin_state  && (scope.row.role != 'ROLE_ADMIN' && scope.row.role != 'ROLE_SUPERADMIN')" @click="adminSet_Btn_Set_1(scope.row.id,'ROLE_ADMIN')" text>设为管理</el-button>
                    <el-button  v-if="scope.row.role != 'ROLE_USER' && super_admin_state  &&  scope.row.role != 'ROLE_SUPERADMIN'" @click="adminSet_Btn_Set_1(scope.row.id,'ROLE_USER')" text>设为用户</el-button>
                </template>
                </el-table-column>
                <el-table-column prop="id" label="编号" width="100" />
                <el-table-column prop="username" label="用户名" width="200" />
                <el-table-column prop="role" label="权限" width="180" />
                <el-table-column prop="email" label="电子邮件" width="180" />
                <el-table-column prop="address" label="地址" width="340" />
                <el-table-column fixed="right" label="操作" width="170">
                    <template #default="scope">
                        <el-button v-if="an_state && !super_admin_state && (scope.row.role != 'ROLE_ADMIN' && scope.row.role != 'ROLE_SUPERADMIN')" link type="primary" size="small" @click="adminSet_Btn_Set_2(scope.row.id)">封禁</el-button>
                        <el-button v-if="scope.row.role != 'banned' && super_admin_state &&  scope.row.role != 'ROLE_SUPERADMIN'" link type="primary" size="small" @click="adminSet_Btn_Set_1(scope.row.id,'banned')">封禁</el-button>
                        <el-button v-if="scope.row.role == 'ROLE_USER' && super_admin_state && (scope.row.role != 'ROLE_ADMIN' && scope.row.role != 'ROLE_SUPERADMIN')" link type="primary" size="small" @click="adminSet_Btn_Set_1(scope.row.id,'ROLE_ADMIN')">设为管理</el-button>
                        <el-button v-if="scope.row.role != 'ROLE_USER' && super_admin_state && scope.row.role != 'ROLE_SUPERADMIN'" link type="primary" size="small" @click="adminSet_Btn_Set_1(scope.row.id,'ROLE_USER')">设为用户</el-button>
                    </template>
                </el-table-column>
            </el-table>  
            <div  style="margin-left: 40%; margin-top: 20px;"> <el-button v-if="page>0" @click="adminSet_Btn_remove" text>上一页</el-button> <el-button disable v-else text>上一页</el-button> <el-input  @keydown.enter.native="adminSet_Btn" style="width: 60px;" v-model="page"/><el-button v-if="nextPage" @click="adminSet_Btn_add" text>下一页</el-button> <el-button v-else text>下一页</el-button></div>
    </el-dialog>
</template>

<style>
    @import "../css/userInform.css";
    @import "../css/input.css"
</style>